<template>
    <div data-tauri-drag-region class="login-bg">
        <el-icon class="close-window" @click="handleClose">
            <CloseBold />
        </el-icon>
        <div class="left-desc" data-tauri-drag-region>
            
        </div>
        <div class="login-container" data-tauri-drag-region>
            <div class="login-content" data-tauri-drag-region>
                <div class="login-header" data-tauri-drag-region>
                    <!-- <img class="logo" src="../../assets/img/logo1.png" alt="" /> -->
                    <img class="logo" data-tauri-drag-region :src="systemIcon" alt="" />
                    <div class="login-title" data-tauri-drag-region>{{settingForm.system_name}}</div>
                </div>
                <el-form :model="param" :rules="rules" ref="login" size="large">
                    <el-form-item prop="username">
                        <el-input v-model="param.username" placeholder="用户名">
                            <template #prepend>
                                <el-icon>
                                    <User />
                                </el-icon>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item prop="password">
                        <el-input
                            type="password"
                            placeholder="密码"
                            v-model="param.password"
                            @keyup.enter="submitForm(login)"
                        >
                            <template #prepend>
                                <el-icon>
                                    <Lock />
                                </el-icon>
                            </template>
                        </el-input>
                    </el-form-item>
                    <!-- <div class="pwd-tips">
                        <el-checkbox class="pwd-checkbox" v-model="checked" label="记住密码" />
                        <el-link type="primary" @click="$router.push('/reset-pwd')">忘记密码</el-link>
                    </div> -->
                    <el-button class="login-btn" type="primary" size="large" @click="submitForm(login)">登录</el-button>
                    <!-- <p class="login-tips">Tips : 用户名和密码随便填。</p> -->
                    <!-- <p class="login-text">
                        没有账号？<el-link type="primary" @click="$router.push('/register')">立即注册</el-link>
                    </p> -->
                </el-form>
            </div>
        </div>

        <!-- 授权对话框 -->
        <AuthDialog
            v-if="showAuthDialog"
            @activated="handleAuthActivated"
            @cancel="handleAuthCancel"
        />
    </div>
</template>

<script setup lang="ts">
import { ref, watch, reactive, onMounted } from 'vue';
import { useTabsStore } from '@/store/tabs';
import { usePermissStore } from '@/store/permiss';
import { useRouter } from 'vue-router';
import { ElMessage, ElNotification } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { Window } from '@tauri-apps/api/window';
import { rsaEncrypt, encryptPassword } from '@/utils/crypto'
import {DoctorService} from '../../api/service/doctorService'
import  siteConfigService  from '@/api/service/siteConfigService'
import { getFileStream} from '@/api/index'
import basisIcon from '@/assets/img/logo1.png';
import type { SiteConfig } from '@/types/siteConfig';
import { useSystemStore } from '@/store/system';
import { verifyLicense } from '@/utils/auth';
import AuthDialog from '@/components/AuthDialog.vue';

const window = Window.getCurrent();

interface LoginInfo {
    username: string;
    password: string;
}

const lgStr = localStorage.getItem('login-param');
const defParam = lgStr ? JSON.parse(lgStr) : null;
const checked = ref(lgStr ? true : false);

const router = useRouter();
const param = reactive<LoginInfo>({
    username: defParam ? defParam.username : 'admin',
    password: defParam ? defParam.password : '',
});

const rules: FormRules = {
    username: [
        {
            required: true,
            message: '请输入用户名',
            trigger: 'blur',
        },
    ],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
};
const permiss = usePermissStore();
const login = ref<FormInstance>();
const showAuthDialog = ref(false);
const isLicenseVerified = ref(false);

// 检查授权状态
const checkLicense = async () => {
    try {
        const verified = await verifyLicense();
        if (!verified) {
            showAuthDialog.value = true;
            ElNotification.warning({
                title: '软件未授权',
                message: '请先完成软件授权才能使用',
                duration: 3000
            });
        } else {
            isLicenseVerified.value = true;
        }
    } catch (error) {
        console.error('授权检查失败:', error);
        showAuthDialog.value = true;
    }
};

// 授权激活成功处理
const handleAuthActivated = () => {
    isLicenseVerified.value = true;
    showAuthDialog.value = false;
    ElMessage.success('授权验证成功，可以正常登录了');
};

// 授权取消处理
const handleAuthCancel = () => {
    handleClose();
};
const submitForm = (formEl: FormInstance | undefined) => {
  // 检查授权状态
  if (!isLicenseVerified.value) {
    ElMessage.warning('请先完成软件授权');
    showAuthDialog.value = true;
    return;
  }
  if (!formEl) return;
  formEl.validate(async (valid: boolean) => {
    if (valid) {
      const doctor = await DoctorService.login(param.username,param.password)
      if(!doctor){
        return ElMessage.warning('账号或者密码不正确')
      }
      ElMessage.success('登录成功');
      // const pwd = rsaEncrypt(param.password)
      //const pwd2 = encryptPassword(param.password)
      sessionStorage.setItem('doctor', JSON.stringify(doctor))
      // console.log(pwd2)s
      localStorage.setItem('vuems_name', param.username);
      const keys = permiss.defaultList[param.username == 'admin' ? 'admin' : 'user'];
      permiss.handleSet(keys);
      router.push('/dashboard');
      if (checked.value) {
        localStorage.setItem('login-param', JSON.stringify(param));
      } else {
        localStorage.removeItem('login-param');
      }
    } else {
      ElMessage.error('登录失败');
      return false;
    }
  });
};

const tabs = useTabsStore();
tabs.clearTabs();

const handleClose = async () => {
    console.log('handleClose')
    await window.close();
}

let settingForm = ref<SiteConfig>({
  id: 1,
  logo: '',
  unit_name: '',
  system_name: '鑫普乐康',
  ip_addr: '',
  port: 0,
})
const system = useSystemStore()
watch(()=> system.systemIcon, (newValue, oldValue) => {
    systemIcon.value = newValue
})

const systemIcon = ref()
systemIcon.value = basisIcon
const getData = async () => {
  try {
    const res = await siteConfigService.getById(1)
    if (res && Object.keys(res).length > 0) {
        settingForm.value = res;
      //console.log('settingForm==', settingForm.value)
    //  localStorage.setItem('systemName',settingForm.value.system_name)
      system.setSystemName(settingForm.value.system_name)
      system.setUnit_name(settingForm.value.unit_name)
      // 如果logo字段有值，加载图片
      if (settingForm.value.logo) {
        try {
          const file = await getFileStream(settingForm.value.logo);
          systemIcon.value = URL.createObjectURL(new Blob([file.buffer])) || basisIcon
        } catch (error) {
          console.warn('无法加载logo图片:', error);
        }
      }
    }
  } catch (error) {
    console.error('加载配置数据失败:', error);
  }
}

// 页面加载时检查授权
onMounted(async () => {
  await getData();
  await checkLicense();
});
</script>

<style scoped>
.login-bg {
    display: flex;
    width: 100%;
    height: 100vh;
}
.left-desc {
    flex: 3;
    /* width: 100%;
    height: 100%; */
    background: url(../../assets/img/login-bg.jpg) center/cover no-repeat;
}

.close-window {
    position: fixed;
    right: 20px;
    top: 20px;
    color: #cbcbcb;
    cursor: pointer;
}

.login-header {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 40px;
}

.logo {
    width: 35px;
    height: 35px;
    user-select: none;
}

.login-title {
    font-size: 26px !important;
    color: #333;
    font-weight: bold;
    user-select: none;
}

.login-container {
    flex: 1;
    /* width: 100%; */
    /* width: 520px; */
    border-radius: 5px;
    background: #fff;
    /* padding: 40px 50px 50px; */
    box-sizing: border-box;
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
}
.login-content {
    width: 380px;
}

.pwd-tips {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 14px;
    margin: -10px 0 10px;
    color: #787878;
}

.pwd-checkbox {
    height: auto;
}

.login-btn {
    display: block;
    width: 100%;
}

.login-tips {
    font-size: 12px;
    color: #999;
}

.login-text {
    display: flex;
    align-items: center;
    margin-top: 20px;
    font-size: 14px;
    color: #787878;
}

.login-container :deep(.el-input--large .el-input__wrapper){
    padding: 0 0 2px 0;
}
.login-container :deep(.el-input__inner) {
    padding: 0 10px;
}
</style>
